$(function () {
    $("#jqGrid").jqGrid({
        url: baseURL + 'order/factoryorder/buyerlist',
        datatype: "json",
        colModel: [
            { label: '操作', name: '', index: '', width: 80, align:'center',
                formatter: function (value, options, row) {
                    if (row.status == 'active'){
                        // 第三方类型:0.中浩紫云;1.自营门店；2.小B;3.工厂
                        var thirdMerchantType = row.thirdMerchantType;
                        // 付款状态：0:未支付,1:已支付
                        var payStatus = row.payStatus;
                        // 收货状态：0:未收货，1:已收货
                        var receivedStatus = row.receivedStatus;
                        // 生产状态 1.待审核;2.待分配;3.生产中;4.生产完成;5.已发货;6.已完成;7.新开单(门店);8.异常(待处理);11.已作废
                        var productionStatus = row.productionStatus;
                        if (thirdMerchantType == 0 || thirdMerchantType == 1){
                            /* 自营门店 (验货确定) */
                            if (productionStatus == 4 && receivedStatus == 0){
                                return '<a href="javascript:;" onclick="return vm.confirmReceive(\'' + row.orderId + '\');">验货确定</a>';
                            }
                        }else if (thirdMerchantType == 2){
                            /* 小B(支付、确认收货) */
                            if (payStatus != '1'){
                                return '<a href="javascript:;" onclick="return vm.orderPay(\''+ row.orderId +'\');">支付</a>';
                            }else if (row.receivedStatus == 0){
                                return '<a href="javascript:;" onclick="return vm.confirmGetGoods(\''+ row.orderId +'\');">确认收货</a>';
                            }
                        }
                    }
                    return '--';
                }
            },
            { label: '订单编号', name: 'orderId', index: 'order_id', width: 120, key: true , align:'center' },
            { label: '原订单号', name: 'originalOrderId', index: 'original_order_id', width: 120, align:'center' },
            /*{ label: '价格详情', name: '', index: '', width: 120, align:'center',
                formatter: function (value, options, row) {
                    return '<a href="javascript:;" onclick="return vm.priceView('+ row.orderId +');">详情</a>';
                }
            },*/
            { label: '商品总额', name: 'totalAmount', index: 'total_amount', width: 70 , align:'center'},
            { label: '订单调价', name: 'discount', index: 'discount', width: 70 , align:'center',
                formatter: function (value, options, row) {
                    return '<a href="javascript:;" style="cursor: pointer;color:red;" onclick="return vm.discountView(\''+ row.orderId +'\',\''+ value +'\');">'+ value +'</a>';
                }
            },
            { label: '应付金额', name: 'payableAmount', index: 'payable_amount', width: 100 , align:'center'},
            { label: '下单时间', name: 'createtime', index: 'createtime', width: 120 , align:'center'},
            { label: '工厂', name: 'supplierName', index: 'supplier_name', width: 150 , align:'center'},
            { label: '分配人', name: 'allotName', index: 'allot_name', width: 70 , align:'center'},
            { label: '订单备注', name: '', index: '', width: 100 , align:'center',
                formatter: function (value, options, row) {
                    return '<a href="javascript:;" onclick="return vm.remarkView(\''+ row.originalOrderId +'\');">查看</a>';
                }
            },
            { label: '用友单号', name: 'yonyouOrderNo', index: 'yonyou_order_no', width: 100 , align:'center',
                formatter: function (value, options, row) {
                    var colMsg = value;
                    if (isBlank(value)){
                        value = '';
                        colMsg = '录入';
                    }
                    return '<a href="javascript:;" style="cursor: pointer;" onclick="return vm.yonyouView(\''+ row.originalOrderId +'\',\''+ value +'\');">'+ colMsg +'</a>';
                }
            },
            { label: '付款状态', name: 'payStatus', index: 'pay_status', width: 80 , align:'center',
                formatter: function (value, options, row) {
                    if (row.payStatus == 1){
                        return '已支付';
                    }else{
                        return '未支付';
                    }
                }
            },
            { label: '生产状态', name: 'productionStatus', index: 'production_status', width: 80 , align:'center',
                formatter: function (value, options, row) {
                    var valueText = "--";
                    if (value == null || value == 1){
                        valueText = "待接单";
                    }else if (value == 3){
                        valueText = "生产中";
                    }else if (value == 4){
                        valueText = "生产完成";
                    }else if (value == 6){
                        valueText = "已完结";
                    }
                    return valueText;
                }
            },
        ],
        viewrecords: true,
        height: window.innerHeight - 120 ,
        rowNum: 25,
        rowList : [25,50,75],
        rownumbers: true,
        rownumWidth: 40,
        autowidth:true,
        multiselect: false,
        pager: "#jqGridPager",
        jsonReader : {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount",
            userdata: "userData"
        },
        prmNames : {
            page:"page",
            rows:"limit",
            order: "order"
        },
        gridComplete:function(){
            //隐藏grid底部滚动条
            $("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" });
        }
    });
    // 显示序号
    $("#jqGrid").jqGrid('setLabel',0, '序号', '{width:80}');
});

var vm = new Vue({
    el:'#rrapp',
    data:{
        showList: true,
        factoryOrder: {},
        orderItemList: [],
        /* 枚举 */
        e:{
            productionStatusEnum: [],
            payTypeEnum: [],
        },
        /* 查询 */
        q:{
            orderId: '',
            supplierName: '',
            originalOrderId: '',
            status: '',
            beginCreatetime: '',
            endCreatetime: '',
            productionStatus: '',
        },
        /* 价格详情 */
        priceTableVisible: false,
        view:{
            quoteProductInfoList: [],
            attributeValueTypeMap: '',
            paperInfoList: [],
            printType: '',
            totalCraftPrice: 0,
            totalPrintPrice: 0,
            totalTotalPrice: 0,
            sharePrice: 0,
            subtract: 0
        },
        /* 订单调价 */
        costFormVisible: false,
        costForm: {
            discount: '',
            remark: '',
            orderId: ''
        },
        /* 用友销售单号 */
        yonyouFormVisible: false,
        yonyouForm: {
            yonyouOrderNo: '',
            orderId: ''
        },
        /* 订单备注 */
        remarkTableVisible: false,
        remarkTable: [],
    },
    methods: {
        /* 订单起始 */
        checkBeginDate: function () {
            WdatePicker({dateFmt:'yyyy-MM-dd',isShowClear:false, onpicking:function (dp) {
                    vm.q.beginCreatetime = dp.cal.getNewDateStr();
                }})
        },
        /* 订单结束 */
        checkEndDate: function () {
            WdatePicker({dateFmt:'yyyy-MM-dd',isShowClear:false, onpicking:function (dp) {
                    vm.q.endCreatetime = dp.cal.getNewDateStr();
                }})
        },
        /* 获取当前日期 */
        dateFormat:function(date) {
            if (typeof date == 'string'){
                date = new Date(date);
            }
            var year=date.getFullYear();
            var month= date.getMonth()+1<10 ? "0"+(date.getMonth()+1) : date.getMonth()+1;
            var day=date.getDate()<10 ? "0"+date.getDate() : date.getDate();
            var hours=date.getHours()<10 ? "0"+date.getHours() : date.getHours();
            var minutes=date.getMinutes()<10 ? "0"+date.getMinutes() : date.getMinutes();
            var seconds=date.getSeconds()<10 ? "0"+date.getSeconds() : date.getSeconds();
            return year+"-"+month+"-"+day+" "+hours+":"+minutes+":"+seconds;
        },
        reset: function () {
            vm.q.orderId = '';
            vm.q.supplierName = '';
            vm.q.originalOrderId = '';
            vm.q.status = '';
            vm.q.beginCreatetime = '';
            vm.q.endCreatetime = '';
            vm.q.productionStatus = '';
            vm.reload();
        },
        query: function () {
            vm.reload();
        },
        reload: function (event) {
            vm.showList = true;
            var page = $("#jqGrid").jqGrid('getGridParam','page');
            $("#jqGrid").jqGrid('setGridParam',{
                page:page,
                postData:{
                    'orderId': vm.q.orderId,
                    'supplierName': vm.q.supplierName,
                    'originalOrderId': vm.q.originalOrderId,
                    'status': vm.q.status,
                    'beginCreatetime': vm.q.beginCreatetime,
                    'endCreatetime': vm.q.endCreatetime,
                    'productionStatus': vm.q.productionStatus,
                },
            }).trigger("reloadGrid");
        },
        /* 价格详情 */
        priceView: function (orderId) {
            vm.priceTableVisible = true;
            $.get(baseURL + "order/factoryorder/orderItemInfo?orderId=" + orderId, function(r){
                vm.view.quoteProductInfoList = r.quoteProductInfoList;
                vm.view.attributeValueTypeMap = r.attributeValueTypeMap;
                vm.view.paperInfoList = r.paperInfoList;
                vm.view.printType = r.printType;
                vm.view.totalCraftPrice = r.totalCraftPrice;
                vm.view.totalPrintPrice = r.totalPrintPrice;
                vm.view.totalTotalPrice = r.totalTotalPrice;
                vm.view.sharePrice = r.sharePrice;
                vm.view.subtract = r.subtract;
            });
        },
        /* 订单取消 */
        orderCancel: function (orderId) {
            this.$confirm('是否确认取消订单?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
                callback: function (f) {
                    if (f == 'confirm'){
                        $.ajax({
                            type: "GET",
                            url: baseURL + "order/factoryorder/orderCancel?orderId=" + orderId,
                            contentType: "application/json",
                            success: function(r){
                                if(r.code == 0){
                                    vm.reload();
                                }else{
                                    alert(r.msg);
                                }
                            }
                        });
                    }
                }
            })
        },
        /* 订单支付 */
        orderPay: function (orderId) {
            this.$confirm('是否确认支付订单?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
                callback: function (f) {
                    if (f == 'confirm'){
                        $.ajax({
                            type: "GET",
                            url: baseURL + "order/factoryorder/orderPay?orderId=" + orderId,
                            contentType: "application/json",
                            success: function(r){
                                if(r.code == 0){
                                    vm.reload();
                                }else{
                                    alert(r.msg);
                                }
                            }
                        });
                    }
                }
            })
        },
        /* 验货确定 */
        orderReceive: function (orderId) {
            this.$confirm('是否确认验货确定?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
                callback: function (f) {
                    if (f == 'confirm'){
                        $.ajax({
                            type: "GET",
                            url: baseURL + "order/factoryorder/orderReceive?orderId=" + orderId,
                            contentType: "application/json",
                            success: function(r){
                                if(r.code == 0){
                                    vm.reload();
                                }else{
                                    alert(r.msg);
                                }
                            }
                        });
                    }
                }
            })
        },
        /* 审核完成（权限收回erp处理） */
        orderFinish: function (orderId) {
            this.$confirm('是否确认审核完成?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
                callback: function (f) {
                    if (f == 'confirm'){
                        $.ajax({
                            type: "GET",
                            url: baseURL + "order/factoryorder/orderFinish?orderId=" + orderId,
                            contentType: "application/json",
                            success: function(r){
                                if(r.code == 0){
                                    vm.reload();
                                }else{
                                    alert(r.msg);
                                }
                            }
                        });
                    }
                }
            })
        },
        discountView: function (orderId, discount) {
            vm.costFormVisible = true;
            vm.costForm.orderId = orderId;
            vm.costForm.discount = discount;
        },
        /* 订单调价 */
        orderDiscount: function () {
            var discount = vm.costForm.discount;
            if (discount == ''){
                alert("调价不能为空");
                return false;
            }

            var remark = vm.costForm.remark;
            if (isBlank(remark)){
                alert("调价原因不能为空");
                return false;
            }
            var orderId = vm.costForm.orderId;
            var postData = {
                orderId: orderId,
                discount: discount,
                remark: remark
            }
            $.ajax({
                type: "POST",
                url: baseURL + "order/factoryorder/orderDiscount",
                contentType: "application/json",
                data: JSON.stringify(postData),
                success: function(r){
                    if(r.code == 0){
                        vm.reload();
                        vm.costFormVisible = false;
                    }else{
                        alert(r.msg);
                    }
                }
            });
        },
        yonyouView: function (orderId, yonyouOrderNo) {
            vm.yonyouForm.orderId = orderId;
            vm.yonyouForm.yonyouOrderNo = yonyouOrderNo;
            vm.yonyouFormVisible = true;
        },
        /* 用友销售单号 */
        orderYonyou: function () {
            $.ajax({
                type: "GET",
                url: baseURL + "order/factoryorder/orderYonyou",
                contentType: "application/json",
                data: {
                    "orderId": vm.yonyouForm.orderId,
                    "yonyouOrderNo": vm.yonyouForm.yonyouOrderNo
                },
                success: function(r){
                    if(r.code == 0){
                        vm.reload();
                        vm.yonyouFormVisible = false;
                    }else{
                        alert(r.msg);
                    }
                }
            });
        },
        remarkView: function (orderId) {
            vm.remarkTableVisible = true;
            $.get(baseURL + "order/orderremarks/orderlist/" + orderId, function(r){
                vm.remarkTable = r.orderRemarks;
            });
        },
        /* 验货确定 */
        confirmReceive: function (orderId) {
            var message = "单号：<span class='text-primary'>"+ orderId +"</span> 是否验货确定？";
            confirm(message, function(){
                $.ajax({
                    type: "GET",
                    url: baseURL + "order/factoryorder/confirmReceive",
                    contentType: "application/json",
                    data: {
                        'orderId': orderId,
                    },
                    success: function(r){
                        if(r.code == 0){
                            alert('操作成功', function(index){
                                vm.reload();
                            });
                        }else{
                            alert(r.msg);
                        }
                    }
                });
            });
        },
        /* 审核完成 */
        auditFinish: function (orderId) {
            var message = "单号：<span class='text-primary'>"+ orderId +"</span> 是否审核完成？";
            confirm(message, function(){
                $.ajax({
                    type: "GET",
                    url: baseURL + "order/factoryorder/auditFinish",
                    contentType: "application/json",
                    data: {
                        'orderId': orderId,
                    },
                    success: function(r){
                        if(r.code == 0){
                            alert('操作成功', function(index){
                                vm.reload();
                            });
                        }else{
                            alert(r.msg);
                        }
                    }
                });
            });
        },

    }
});

